<?php
/* Common */
require '../common.php';
require '../database.php';
require 'db_data_loader.php';
db_connect();
$support_measures = get_subdivisios_measures_associative();

/* Configurations */
if (count($_POST)) {
    $year = $_POST['year'];
    $month = $_POST['month'];
    $max_count = $_POST['maxCount'];
    $n = $_POST['n'];
    $n_support_measures = $_POST['nSupport'];
} else {
    $year = 2011;
    $month = 1;
    $max_count = 100;
    $n = 3;
    $n_support_measures = count($support_measures);
}

?>
<form action="#" method="post">
    Start year: <input name="year" value="<?=$year;?>"/><br/>
    Start month: <input name="month" value="<?=$month;?>"/><br/>
    Month count: <input name="n" value="<?=$n;?>"/><br/>
    Max applications count per per month: <input name="maxCount" value="<?=$max_count;?>"/><br/>
    Max support measures: <input name="nSupport" value="<?=$n_support_measures;?>"/><br/>
    <input name="drop" id="drop" type="checkbox" value="yes" checked="checked"/><label for="drop">Remove old data</label><br/>
    <input type="Submit"/>
</form>

<?
if (count($_POST)) {
    /* Generating data */
    $drop_old = $_POST['drop'];
    $first = true;
    $received_sum = array();
    $sql = "-- historical_quantities --\n\n";
    $sql .= "INSERT INTO historical_quantities (`date`, measure_code, received, administrated) VALUES\n";
    $left = 0;
    for ($i = 0; $i < $n; $i++) {
        $iSupport = 0;
        foreach (array_keys($support_measures) as $support_measure) {
            if ($first) {
                $first = false;
            } else {
                $sql .= ",-- left $left\n";
            }

            $received = rand(0, $max_count);
            if (array_key_exists($support_measure, $received_sum)) {
                $received_sum[$support_measure] += $received;
            } else {
                $received_sum[$support_measure] = $received;
            }
            $addministrated = rand(floor($received_sum[$support_measure] / 2), $received_sum[$support_measure]);
            $received_sum[$support_measure] -= $addministrated;
            $left = $received_sum[$support_measure];
            $sql .= "('$year-$month-01', '$support_measure', $received, $addministrated)";
            $iSupport++;
            if ($iSupport > $n_support_measures) {
                break;
            }
        }
        $month++;
        if ($month > 12) {
            $year++;
            $month = 1;
        }
        $sql .= "\n";
    }
    $sql .= ';';
    
    /* Saving to database and output */
    if ($drop_old) {
        mysql_query("TRUNCATE historical_quantities;");
    }
    mysql_query($sql);
    echo 'Saved to DB';
    echo '<pre>' . htmlspecialchars($sql) . '</pre>';
    echo 'Not administrated applications:<br/>';
    foreach ($received_sum as $support_measure=>$count) {
        echo "&nbsp;<b>$support_measure</b> $count<br/>";
    }
}

db_close();
?>
<a href="../">Pagrindinis</a>